package com.amado.easyui2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amado.easyui2.constant.GlobalConstants;
import com.amado.easyui2.domain.CoachStaffEntity;
import com.amado.easyui2.service.CoachStaffService;
import com.amado.easyui2.service.impl.CoachStaffServiceImpl;
import com.amado.easyui2.servlet.DrivingSchoolServlet.Result;
import com.amado.easyui2.util.JsonUtil;
import com.amado.easyui2.vo.Page;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CoachStaffServlet extends HttpServlet {
	private CoachStaffService coachStaffService = new CoachStaffServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method=arg0.getParameter("method");
		if("add".equals(method)) {
			add(arg0,arg1);
		}else if("update".equals(method)) {
			update(arg0,arg1);
		}else if("edit".equals(method)) {
			edit(arg0,arg1);
		}else if("delete".equals(method)) {
			delete(arg0,arg1);
		}else if("query".equals(method)) {
			query(arg0,arg1);
		}else if("login".equals(method)) {
			login(arg0,arg1);
		}
	}

	private void add(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		
		CoachStaffEntity CoachStaffInfo = JsonUtil.jsonToBean(strJson, CoachStaffEntity.class);
		coachStaffService.add(CoachStaffInfo);
	}
	private void update(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		CoachStaffEntity coachInfo = JsonUtil.jsonToBean(strJson, CoachStaffEntity.class);
		Long id=coachInfo.getId();
		String drivingSchoolName=coachInfo.getDrivingSchoolName();
		String deleteLogo=coachInfo.getDeleteLogo();
		String coachName=coachInfo.getCoachName();
		String coachNumber=coachInfo.getCoachName();
		String coachIdCard=coachInfo.getCoachIdCard();
		String coachSex=coachInfo.getCoachSex();
		String coachDateBirth=coachInfo.getCoachDateBirth();
		String nation=coachInfo.getNation();
		String quasiDrivingType=coachInfo.getQuasiDrivingType();
		String mustTeachModels=coachInfo.getMustTeachModels();
		String placeOfDomicile=coachInfo.getPlaceOfDomicile();
		String phone=coachInfo.getPhone();
		String referenceStatus=coachInfo.getReferenceStatus();
		String returnMessage=coachInfo.getReturnMessage();
		String popedom=coachInfo.getPopedom();
		String province=coachInfo.getProvince();
		String city=coachInfo.getCity();
		String contactAddress=coachInfo.getContactAddress();
		String mustTeachClasses=coachInfo.getMustTeachClasses();
		String learnHistory=coachInfo.getLearnHistory();
		String socialSecurityNumber=coachInfo.getSocialSecurityNumber();
		Date drivingLicenceStatsTime=coachInfo.getDrivingLicenceStatsTime();
		Date pactStatsTime=coachInfo.getPactStatsTime();
		Date pactEndTime=coachInfo.getPactEndTime();
		String workingState=coachInfo.getWorkingState();
		Date certificateTime=coachInfo.getCertificateTime();
		Date validTime=coachInfo.getValidTime();
		String learnCardNumber=coachInfo.getLearnCardNumber();
		Date createTime=coachInfo.getCreateTime();
		Date updateTime=coachInfo.getUpdateTime();
		String createName=coachInfo.getCreateName();
		String updateName=coachInfo.getUpdateName();
		CoachStaffEntity coachStaff=new CoachStaffEntity(id, drivingSchoolName, coachName, coachNumber, coachIdCard, coachSex,
				coachDateBirth, nation, quasiDrivingType, mustTeachModels, placeOfDomicile, phone,
				referenceStatus, returnMessage, popedom, province, city, contactAddress, mustTeachClasses,
				learnHistory, socialSecurityNumber, drivingLicenceStatsTime, pactStatsTime, pactEndTime,
				workingState, certificateTime, validTime,deleteLogo, learnCardNumber,createTime,updateTime,createName,updateName);
		coachStaffService.update(coachStaff);
	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		List<CoachStaffEntity> list = coachStaffService.list();
		for (CoachStaffEntity coachStaff : list) {
			if (coachStaff.getId().equals(id)) {
				CoachStaffEntity coachId = coachStaff;
				PrintWriter out = arg1.getWriter();
				out.print(mapper.writeValueAsString(coachId));
				break;
			}
		}
		
	}

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
//		String delete = arg0.getParameter("delete");
//		if (delete != null && delete.trim() != "") {
//			coachStaffService.delete(Long.valueOf(delete));
//			arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
//		} else {
//			arg1.getWriter().print(JsonUtil.beanToJson(new Result("0", "参数错误")));
//		}
		PrintWriter out=arg1.getWriter();
		try {
			String ids = arg0.getParameter("ids");
			if (ids != null) {
				String[] idAray = ids.split(",");
				if (idAray.length > 5) {
					out.print(mapper.writeValueAsString(new Result("2", "删除数据不能超过5个")));
				} else {
					List<Long> idList = new ArrayList<>();
					for (String tempId : idAray) {
						// idList.add(Long.valueOf(Long.parseLong(tempId)));
						// idList.add(Long.parseLong(tempId));
						idList.add(Long.valueOf(tempId));
					}
					coachStaffService.delete(idList);
					// 1:成功
					out.print(mapper.writeValueAsString(new Result()));
				}
			}
		} catch (Exception e) {
			out.print(mapper.writeValueAsString(new Result("2", e.getMessage())));
		}
		
	}
	class Result {
		// 0失败，1成功
		private String resultCode = "1";
		private String resultMessage = "成功";

		public Result() {
		}

		public Result(String resultCode, String resultMessage) {
			super();
			this.resultCode = resultCode;
			this.resultMessage = resultMessage;
		}

		public String getResultCode() {
			return resultCode;
		}

		public void setResultCode(String resultCode) {
			this.resultCode = resultCode;
		}

		public String getResultMessage() {
			return resultMessage;
		}

		public void setResultMessage(String resultMessage) {
			this.resultMessage = resultMessage;
		}
	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Page page = new Page();
		String strPage = arg0.getParameter("page");
		String strRows = arg0.getParameter("rows");
		int page1= strPage==null?1:Integer.parseInt(strPage);//
		int rows = strRows==null?5:Integer.parseInt(strRows);
		String cn = arg0.getParameter("cn");
		String cIC = arg0.getParameter("cIC");
		page.setCurrentPage(page1);
		page.setRowSize(rows);
		Page<CoachStaffEntity> pageList = coachStaffService.listAll(cn, cIC, page);
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(pageList));
		
	}

	private void login(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		String coachName=arg0.getParameter("coachName");
		String coachIdCard=arg0.getParameter("coachIdCard");
		CoachStaffEntity coachInfo=new CoachStaffEntity(coachName,coachIdCard);
		String verifyCode = arg0.getParameter("VerificationCode");
		String sessionVerifyCode = (String) arg0.getSession(true).getAttribute(verifyCode);
		if (sessionVerifyCode != null && sessionVerifyCode.equals(verifyCode)) {
			arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
			return;
		}
		List<CoachStaffEntity> list = coachStaffService.getCoach(coachInfo);
		if (list != null) {
			list.forEach(e -> {
				if (e.getCoachName() != null && !e.getCoachName().equals("") && e.getCoachIdCard()!= null
						&& !e.getCoachIdCard().equals("")) {
					arg0.getSession().setAttribute(GlobalConstants.SESSION_USER, coachName);
					try {
						arg1.sendRedirect("index.jsp");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					arg0.setAttribute("msg", "用户名或密码错误");
					try {
						arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
					} catch (ServletException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
	}

}
